import { loginReq, logoutReq, registerReq } from "@/api/userReq";
import store from "@/store";
import { mutationsType } from "@/store/user/types";
import { docCookies } from "@/utils/docCookie";
import { goLogin } from "@/utils/routerGuard";
import { Random } from "mockjs";
import { LoginForm, RegisterForm } from "model";
import md5 from "md5";

export const login = async (loginForm: LoginForm, realCaptcha: string) => {
  if (md5(loginForm.captcha) === realCaptcha) {
    await loginReq(loginForm)
      .then(() => {
        store.commit("user/" + mutationsType.SAVE_USER_INFO, {
          username: loginForm.username,
        });
        docCookies.setItem("session_token", Random.guid(), 36000);
      })
      .catch((err) => {
        console.log(err.message);
        throw new Error("登录失败");
      });
  } else {
    throw new Error("验证码错误");
  }
};

export const register = async (registerForm: RegisterForm) => {
  await registerReq(registerForm);
};

export const logout = async () => {
  await logoutReq()
    .then(() => {
      store.commit("user/" + mutationsType.CLEAR_USER_INFO);
      goLogin();
    })
    .catch((err) => {
      console.log(err.message);
      goLogin();
    });
};
